<template>
	<view>
		<global-contact></global-contact>
		<view class="tab">
			<view class="items" @click="saveImg">
				<u-icon name="download" color="#000000" size="20"></u-icon>
				<text>保存</text>
			</view>
			<view class="items" @click="posterImg">
				<u-icon name="share-square" color="#000000" size="20"></u-icon>
				<text>发布</text>
			</view>
		</view>
		 
		
		<view class="pick poster" id="poster"> 
		 
			<canvas  canvas-id="myCanvas"  :style="{ width: canvasW + 'px', height: canvasH + 'px' }" id="myCanvas"></canvas> 
			
			<!-- <cover-view> -->
				
			<view class="itemWrap" :style="{'justify-content':realVal=='left'?'flex-start':realVal=='center'?'center':'flex-end'}">
				<view class="itemInfo">
					<view class="uploadImg"  @click="chooseImg" :style="{'opacity':tempimg?0:1}"  v-if="tempimg">
						<image :src="tempimg" class="dataImg" mode="aspectFill"></image> 
					</view>
					<view class="uploadImg" @click="chooseImg" v-else style="background-color: #FFFFFF; ">
						<image class="icon" src="https://www.atuanjian.com/appletStatic/static/need/up.png" mode=""></image>
						<text>二维码</text> 
					</view>
					<view class="inputWrap" :style="{'opacity':namevalue?0:1}">昵称</view> 
				</view>
			</view>
			<!-- </cover-view> -->
			
		</view> 
		<!-- tools -->
		<view class="tools">
			<view class="selecItem">
				<text>对齐方式</text>
				<u-radio-group placement="row" v-model="sortValue" iconPlacement="right" @change="groupChange">
					<u-radio activeColor="red" v-for="(item, index) in radioList"
					  :key="index"
					  :label="item.name"
					  :name="item.name"></u-radio> 
				</u-radio-group>
			</view>
			<view class="selecItem">
				<text>二维码</text>
				 <u-switch v-model="hasCode" @change="changeCode" activeColor="#f56c6c" size="20"></u-switch>
			</view>
			<view  class="selecItem" v-if="hasCode" @click="chooseImg">
				<text>选择二维码</text>
				 <u-icon name="arrow-right"></u-icon>
				
			</view>
			<view class="selecItem">
				<text>个人信息</text>
				 <u-switch v-model="hasInfo" @change="changeInfo" activeColor="#f56c6c" size="20"></u-switch>
			</view>
			<block v-if="hasInfo">
				<view class="selecItem">
					<text>昵称：</text>
					 <u--input
					     placeholder="请输入内容"
					     border="bottom" 
						 :maxlength="10"
						 v-model="namevalue"
						@change="changeVal"
					   ></u--input>
				</view>
				<view class="selecItem" @click="selectorColor">
					<text>字体颜色：</text>
					<text>{{sizeColor}}</text>
					 

				</view>
			</block>
		</view>
		  
	 
		
	</view>
</template>

<script>
 
	import { getPosterDetail,posterUse } from '@/utils/request.js' 
	// getPosterDetail
	let context
	export default {
		data() {
			return {
				showImg:'',
				info:null,
				id:'',
				// 
				canvasW:0,
				canvasH:0,
				
				 obj:{
					 '居左':'left',
					 '居中':'center',
					 '居右':'right'
				 },
				 sortValue:'居右',
				 realVal:'right',
				 radioList:[{
					 name:'居左'
				 },{
					 name:'居中'
				 },{
					 name:'居右' 
				 }],
				 
				 hasCode:true,
				  
				 hasInfo:true,
				 namevalue:'',
				 
				 
				 goodsImg:'',
				 
				 tempimg:'',
				 ewmImg:'',
				 
				 show:false,
				 sizeColor:'#FFFFFF', 
				 
				 timer:null
			}
		}, 
		methods: {
			// 1
			groupChange(e){
				this.realVal=this.obj[e]
				console.log('排列',e,this.realVal)
				 this.drawCanvas()
			},
			// 2
			changeCode(e){
				console.log('e',e)
				this.drawCanvas()
			},
			// 3
			changeInfo(e){
				console.log('e',e)
				this.drawCanvas()
			},
			// 4 nick
			changeVal(e){ 
				console.log('e',e) 
				this.drawCanvas()
			}, 
			drawCanvas(){
				if(this.timer){
					clearTimeout(this.timer)
					this.timer=null
				}
				this.timer=setTimeout(()=>{
					context.drawImage(this.goodsImg,0,0,this.canvasW,this.canvasH);   //插入图片
					
					if(this.hasCode&&this.ewmImg){ 
						let imgNum=''
						if(this.realVal=='right'){
							imgNum=this.canvasW-80
							
						}else if(this.realVal=='center'){
							imgNum=this.canvasW/2-30
						}else if(this.realVal=='left'){
							imgNum=20
						}
						context.drawImage(this.ewmImg,imgNum,this.canvasH-100,60,60);   //插入图片
					} 
					
					if(this.hasInfo){
						let txtH=''
						if(this.realVal=='right'){
							txtH=this.canvasW-20
						}else if(this.realVal=='center'){
							txtH=this.canvasW/2
						}else if(this.realVal=='left'){
							txtH=20
						}
						context.setFontSize(14) // 字号
						context.setFillStyle(this.sizeColor) // 字体颜色
						context.setTextBaseline(this.realVal) 
						context.setTextAlign(this.realVal)
						// 170
						context.fillText(this.namevalue, txtH,this.canvasH-17); // （文字，x，y 
					}
					context.draw()
				},600)
				
			},
			// color 
			selectorColor(){
				uni.navigateTo({
					url:'/pagesA/dynamic/selectColor'
				})
			}, 
			// toimg
			posterImg(){
				if(!uni.getStorageSync('userInfo')){
					uni.showToast({
						icon:'none',
						title:'请先登录'
					})
					return
				}
				uni.showLoading({
					title:'图片生成中...' 
				})
				let userInfo=uni.getStorageSync('userInfo') 
				let t=this;
				uni.canvasToTempFilePath({
				  x: 0,
				  y: 0,
				  width: this.canvasW,
				  height: this.canvasH,
				  // destWidth: this.canvasW,
				  // destHeight: this.canvasH,
				  canvasId: 'myCanvas',
				  success: function(res) { 
				    console.log('282',res.tempFilePath) 
					 uni.uploadFile({
						url: t.$config.upLoadApi+'file/imageUpload',  
						filePath: res.tempFilePath,
						name: 'file',
						formData: {
							file:res.tempFilePath,
							token:JSON.parse(userInfo).token,
						},
						success: (res) => {
							uni.hideLoading()
							let data=JSON.parse(res.data) 
							if(data.code==403){
								uni.showToast({
									title:data.msg,
									icon:'none',
									duration:3000
								})
								return 
							}else{
								console.log('result',data)
								uni.navigateTo({
									url:'/pagesA/dynamic/submit?url='+data.path
								})
							}
						}
					});  
				  },
				})
			},  
			getImageInfo(image) {
				return new Promise((req, rej) => {
					uni.getImageInfo({
						src: image,
						success: function(res) {
							req(res)
						},
					});
				})
			},
			// -------------------------------- 
			async posterUse(data){
				return await posterUse(data)
			}, 
			saveApi(){
				if(!uni.getStorageSync('userInfo')){
					uni.showToast({
						icon:'none',
						title:'请先登录'
					})
					return
				}
				let userInfo=uni.getStorageSync('userInfo') 
				let data={
					token:userInfo?JSON.parse(userInfo).token:'',
					id:this.id
				}
				this.posterUse(data).then(res=>{
					uni.showToast({
						title:'保存成功',
						icon:'none'
					})
				})
			},
			
			saveImg(){
				let t=this;
				uni.canvasToTempFilePath({
				  x: 0,
				  y: 0,
				  width: this.canvasW,
				  height: this.canvasH,
				  destWidth:1200,
				  destHeight:2100,
				  // destWidth: this.canvasW*20,
				  // destHeight: this.canvasH*20,
				  canvasId: 'myCanvas',
				  success: function(res) {
				    // 在H5平台下，tempFilePath 为 base64
				    console.log('282',res.tempFilePath)
						
						// uni.downloadFile({
						// 	url:res.tempFilePath,
						// 	success: res => {
						// 		if (res.statusCode === 200) {
									
									uni.saveImageToPhotosAlbum({
										filePath: res.tempFilePath,
										success: function() {
											// this.tools.toast('保存成功');
											t.saveApi()
										},
										fail: function() {
											// this.tools.toast('保存失败，请稍后重试');
											uni.showToast({
												title:'保存失败',
												icon:'none'
											})
										}
									});
									
								// } else {
								// 	// this.tools.toast('下载失败');
								// 	uni.showToast({
								// 		title:'下载失败',
								// 		icon:'none'
								// 	})
								// }
						// 	}
						// });
				  } 
				})
			
			
				// uni.canvasToTempFilePath({ // 保存canvas为图片
				// 	canvasId: 'myCanvas',
				// 	quality: 1,
				// 	complete: function(res) {
				 
				// 		console.log('保存canvas',res.tempFilePath)								
				// 	} ,
				// })
			
			},
			async getPosterDetail(data){
				return await getPosterDetail(data)
			}, 
			getDetail(){
				let userInfo=uni.getStorageSync('userInfo') 
				if(!userInfo){
					uni.showToast({
						icon:'none',
						title:'请先登录'
					})
					return
				}
				let data={
					token:JSON.parse(uni.getStorageSync('userInfo')).token,
					id:this.id
				}
				this.getPosterDetail(data).then(res=>{
					this.info=res
					// this.drawImg()
					setTimeout(()=>{ 
						// this.drawCanvas()
						this.canvasShow()
					},300)
					console.log(res)
				})
			},
			canvasShow() {
				let imgUrl=this.showImg+this.info.img 
				  context = uni.createCanvasContext('myCanvas', this);  //canvas-id='firstCanvas'
				  let t=this
				 uni.getImageInfo({
				       src:imgUrl,
				       success:res=>{
				            // console.log(`缓存地址：${res.path}`); 
							// t.bgImg=res.path
							t.goodsImg=res.path
				 　　　　　　context.drawImage(res.path,0,0,this.canvasW,this.canvasH);   //插入图片
							context.draw()
							 
				     },
				       fail:res=>{
				            console.log(`缓存失败：${res.errMsg}`);     
				     } 
				 })
				 
			},
			chooseImg(){
				uni.navigateTo({
					url:'/pagesA/dynamic/cutImg'
				})
			 
			},
			 
			 
		},
		onLoad(option) {
			this.showImg=this.$config.showImgApi;
			this.id=option.id
			if(!uni.getStorageSync('userInfo')){
				uni.navigateTo({
					url:'/pagesB/login/login'
				})
				return
			}
			this.getDetail()
			
			// let device=uni.getSystemInfo();
			// let width=device.windowWidth;
			// //然后需要确定比例，设计图一般都是750的屏幕，这里是375px
			// this.baseWidth=width / 375;
			uni.getSystemInfo({
				success: res=>{
					// 画布宽度
					this.canvasW = res.windowWidth-120; 
					// this.canvasH = res.windowHeight - 260;
					this.canvasH = 495
					 
				}
			});

		},
		onShow() {
			if(!uni.getStorageSync('userInfo')){return}
			uni.$on('updateData',data=>{
				console.log('色彩',data)
				this.sizeColor=data
				 
				this.drawCanvas()
			})
			// updateImg
			uni.$on('updateImg',data=>{
				console.log('img',data)
				uni.getImageInfo({
					  src:data,
					  success:res=>{
						console.log(`缓存地址506：${res.path}`); 
						this.ewmImg=res.path
						this.tempimg=res.path
						this.drawCanvas()
 
								 
					},
					  fail:res=>{
						   console.log(`缓存失败：${res.errMsg}`);     
					} 
				})
				
			})
		},
		onUnload() {
			uni.$off('updateData')
			uni.$off('updateImg')
		},
		
		// mounted() {
		// 	const t=this
		// 	const query = uni.createSelectorQuery().in(this);
		// 	query.select('#poster').boundingClientRect(dom => {
		// 	  // console.log("得到布局位置信息" + JSON.stringify(dom));
		// 	  t.domHtml=dom
		// 	  // console.log("节点离页面顶部的距离为" + dom.top);
			  
		// 	}).exec();
		// },
	}
</script>

<style lang="scss">
	
	page{
		background-color: #F8F8F8;
	}
	.tab{
		padding: 0 100rpx;
		background-color: #FFFFFF;
		box-shadow: 0px 0px 10rpx 1rpx rgba(47, 46, 62, 0.2);
		margin-bottom: 10rpx;
		display: flex;
		justify-content: space-between;
		.items{
			display: flex;
			justify-content: flex-start;
			align-items: center;
			height: 100rpx;
		}
	}
	
	.poster{
		// width: 560rpx;
		// height: 800rpx;
		margin: 50rpx auto 0;
		position: relative;
		.canvasImg{width: 100%;height: 100%;}
	}
	.itemWrap{
		// width: 93%;
		width: 560rpx;
		padding: 0 30rpx;
		box-sizing: border-box;
		position: absolute;
		bottom: 30rpx; 
		left: 0;
		right: 0;
		margin: auto;
		display: flex;
		z-index: 9999;
		.itemInfo{
			width: 120rpx;
			.uploadImg{
				position: relative;
				width: 120rpx;
				height: 120rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				flex-direction: column;
				margin-bottom: 10rpx;
				.dataImg{
					width: 120rpx;
					height: 120rpx;
					position: absolute;
					top: 0;
					left: 0;
				}
				.icon{
					width: 50rpx;
					height: 50rpx;
					margin-bottom: 10rpx;
				}
				text{
					font-size: 22rpx;
				}
			}
			.inputWrap{
				text-align: right;
				color: #FFFFFF;
				font-size: 24rpx;				 
			}
		}
	}
	.u-radio {
		margin-left: 20rpx;
	}
	.u-radio__text{
		margin-right: 10rpx;
	}
	.tools{
		padding:0 30rpx 30rpx;
		margin-top: 40rpx;
	}
	.selecItem{
		background-color: #FFFFFF;
		border: 1px solid #F8F8F8;
		padding: 30rpx 20rpx;
		margin: 2px 0;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	.u-radio-group{flex: none!important;}
	#myCanvas{
		// width: 560rpx;
		// height: 800rpx;
		// border: 1px solid #CCCCCC;
		margin: auto;
	}

	// .wrap{
	// 	// padding-top: 30rpx;
	// 	display: flex;
	// 	justify-content: flex-start;
	// 	align-items: center;
	// 	flex-flow: column nowrap;
	// 	text-align: center;
	// 	// image{
	// 	// 	width: 660rpx;
	// 	// 	height: 800rpx;
	// 	// 	margin-bottom: 30rpx;
	// 	// 	border-radius: 10rpx;
	// 	// }
	// 	position: relative;
	// 	.uploadImg{
	// 		width: 130rpx;
	// 		height: 130rpx;
	// 		position: absolute;
	// 		bottom: 210rpx;
	// 		right: 100rpx;
	// 		z-index: 999;
	// 		text-align: center;
	// 		background-color: #FFFFFF;
	// 		display: flex;
	// 		justify-content:center;
	// 		align-items: center;
	// 		flex-direction: column;
			
	// 		.icon{
	// 			width: 60rpx;
	// 			height: 60rpx;
	// 		}
	// 		text{
	// 			color: #000000;
	// 		}
	// 		.img{
	// 			display: block;
	// 			width: 100%;
	// 			height: 100%;
	// 		}
	// 	} 
	// 	.items{
	// 		font-size: 24rpx;
	// 	}
		
	// }
	// .txt{
	// 	margin-top: 20rpx;
	// 	margin-left: 40rpx;
	// 	margin-right: 40rpx;
	// 	padding-bottom: 10rpx;
	// 	border-bottom: 1px solid #CCCCCC;
	// 	display: flex;
	// 	justify-content: space-between;
	// 	align-items: center;
	// }
	.u_input_box{
		padding: 0 40rpx;
		
	}
	.u-input{
		padding-top: 0;
		padding-bottom: 0;
		border: none!important;
	}
</style>
